package ubadb.core.components.bufferManager.bufferPool.replacementStrategies.touchCount;

import java.util.Calendar;
import java.util.Date;

import ubadb.core.common.Page;
import ubadb.core.components.bufferManager.bufferPool.BufferFrame;
import ubadb.core.exceptions.BufferFrameException;

public class TouchCountBufferFrame extends BufferFrame {
	
	private Integer touchCount = 0;
	private Date creationDate;
	private Date modificationDate;
	private Double _db_aging_touch_time = TouchCountReplacementStrategy.DEFAULT_AGING_TOUCH_COUNT;
	
	public TouchCountBufferFrame(Page page) {
		super(page);
		this.creationDate = new Date();
		this.modificationDate = new Date();
	}

	TouchCountBufferFrame(Page page, Double _db_aging_touch_time) {
		super(page);
		this.creationDate = new Date();
		this.modificationDate = new Date();
		this._db_aging_touch_time = _db_aging_touch_time;
	}
	
	public void pin() {
		super.pin();
		// If the amount of time in "_db_aging_touch_time" has expired
		if (agingTouchTimeExpired()) {
			touchCount++;
			modificationDate = new Date();
		}
	}
	
	public void unpin() throws BufferFrameException {
		super.unpin();
		// If the amount of time in "_db_aging_touch_time" has expired
		if (agingTouchTimeExpired()) {
			touchCount++;
			modificationDate = new Date();
		}
	}

	private boolean agingTouchTimeExpired() {
		// Check whether the amount of time between "modificationDate" and now is greater than "_db_aging_touch_time" (multiplied by 1000 to get milliseconds)
		Calendar today = Calendar.getInstance();
		return today.getTime().getTime() - modificationDate.getTime() > _db_aging_touch_time * 1000;
	}

	public Integer getTouchCount() {
		return touchCount;
	}

	public void setTouchCount(Integer touchCount) {
		this.touchCount = touchCount;
	}

	public Date getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}

	public Date getModificationDate() {
		return modificationDate;
	}

	public void setModificationDate(Date modificationDate) {
		this.modificationDate = modificationDate;
	}

}